<template>
  <div class="global-search" ref="searchContainer">
    <el-input
      v-model="searchKeyword"
      placeholder="搜索文件和文件夹..."
      :prefix-icon="Search"
      clearable
      :loading="isSearching"
      @input="handleInput"
      @focus="handleFocus"
      @blur="handleBlur"
      @keydown="handleKeydown"
      @clear="handleClear"
    />
    
    <!-- 搜索建议下拉框 -->
    <div
      v-if="showDropdown && searchKeyword.trim()"
      class="search-dropdown"
      @mousedown.prevent
      @mouseup.prevent
    >
      <!-- 加载状态 -->
      <div v-if="isSearching" class="search-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>搜索中...</span>
      </div>

      <!-- 搜索建议 -->
      <div v-else-if="suggestions && suggestions.length > 0">
        <!-- 文件建议 -->
        <div
          v-for="(item, index) in (suggestions || [])"
          :key="item.id"
          :class="['search-item', { active: selectedIndex === index }]"
          @click="handleItemClick(item)"
          @mouseenter="selectedIndex = index"
        >
          <div class="item-icon">
            <el-icon v-if="item.type === 'folder'"><Folder /></el-icon>
            <el-icon v-else-if="item.icon === 'word'"><Document /></el-icon>
            <el-icon v-else-if="item.icon === 'pdf'"><Document /></el-icon>
            <el-icon v-else><Document /></el-icon>
          </div>
          
          <div class="item-content">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-meta">
              <span v-if="item.parentFolder" class="parent-folder">{{ item.parentFolder }}</span>
              <span v-if="item.size" class="file-size">{{ item.size }}</span>
              <span v-if="item.modifiedAt" class="modified-time">{{ item.modifiedAt }}</span>
            </div>
          </div>
        </div>
        
        <!-- 查看更多结果 -->
        <div
          v-if="totalCount > (suggestions?.length || 0)"
          :class="['search-item', 'more-results', { active: selectedIndex === (suggestions?.length || 0) }]"
          @click="handleViewMore"
          @mouseenter="selectedIndex = (suggestions?.length || 0)"
        >
          <div class="item-icon">
            <el-icon><Search /></el-icon>
          </div>
          <div class="item-content">
            <div class="item-name">查看"{{ searchKeyword }}"的所有搜索结果</div>
            <div class="item-meta">共找到 {{ totalCount }} 个结果</div>
          </div>
        </div>
      </div>

      <!-- 无结果状态 -->
      <div v-else class="no-results">
        <div class="no-results-text">未找到相关文件</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Loading, Folder, Document } from '@element-plus/icons-vue'
import { searchApi, type SearchSuggestion } from '@/api/modules/search'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const isSearching = ref(false)
const showDropdown = ref(false)
const suggestions = ref<SearchSuggestion[]>([]) // 确保初始化为空数组
const totalCount = ref(0)
const selectedIndex = ref(-1)
const searchContainer = ref()

// 防抖定时器
let searchTimer: any = null

// 监听下拉框显示状态变化（调试用）
// watch(showDropdown, (newValue, oldValue) => {
//   console.log('🔍 showDropdown变化:', {
//     from: oldValue,
//     to: newValue,
//     stack: new Error().stack?.split('\n')[2]?.trim()
//   })
// })

/**
 * 处理用户输入事件
 * 实现300ms防抖，避免频繁API调用
 */
const handleInput = () => {
  // console.log('🔍 搜索输入:', searchKeyword.value)

  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  if (!searchKeyword.value.trim()) {
    // console.log('🔍 搜索关键词为空，关闭下拉框')
    showDropdown.value = false
    suggestions.value = []
    return
  }

  isSearching.value = true
  // console.log('🔍 开始搜索，显示下拉框')
  showDropdown.value = true

  // 300ms防抖
  searchTimer = setTimeout(() => {
    performSearch()
  }, 300)
}

/**
 * 执行搜索API调用
 * 获取搜索建议并更新界面状态
 */
const performSearch = async () => {
  try {
    // 调用搜索建议API
    const response = await searchApi.getSuggestions({
      q: searchKeyword.value,
      limit: 8
    })

    // console.log('🔍 搜索API响应:', response)

    // 检查响应数据结构 - 需要访问response.data.suggestions
    if (response && response.data && response.data.suggestions) {
      suggestions.value = response.data.suggestions
      totalCount.value = response.data.totalCount || response.data.suggestions.length

      // console.log('🔍 成功解析搜索结果:', {
      //   suggestionsLength: suggestions.value.length,
      //   totalCount: totalCount.value
      // })

      // 如果有搜索结果，确保下拉框显示
      if (suggestions.value.length > 0) {
        // console.log('🔍 有搜索结果，确保下拉框显示')
        showDropdown.value = true
      }
    } else {
      // 如果数据结构不正确，初始化为空数组
      // console.log('🔍 数据结构不正确，初始化为空数组', response)
      suggestions.value = []
      totalCount.value = 0
    }

    selectedIndex.value = -1

  } catch (error) {
    console.error('搜索失败:', error)

    // 如果API失败，使用模拟数据
    suggestions.value = [
      {
        id: 'file_1',
        type: 'file',
        name: `${searchKeyword.value}相关文档.docx`,
        path: `/我的文档/${searchKeyword.value}相关文档.docx`,
        icon: 'word',
        size: '45KB',
        modifiedAt: '2025-07-01',
        parentFolder: '我的文档',
        folderId: '0'
      }
    ]
    totalCount.value = 5
    selectedIndex.value = -1

    // console.log('🔍 使用模拟数据:', {
    //   suggestionsLength: suggestions.value.length,
    //   totalCount: totalCount.value
    // })

  } finally {
    isSearching.value = false
    // console.log('🔍 搜索完成，下拉框状态:', {
    //   showDropdown: showDropdown.value,
    //   suggestionsLength: suggestions.value?.length || 0,
    //   searchKeyword: searchKeyword.value
    // })
  }
}

/**
 * 处理搜索框焦点事件
 * 获得焦点时显示已有的搜索结果
 */
const handleFocus = () => {
  // console.log('🔍 搜索框获得焦点')
  if (searchKeyword.value.trim() && suggestions.value && suggestions.value.length > 0) {
    showDropdown.value = true
  }
}

/**
 * 处理搜索框失去焦点事件
 * 延迟关闭下拉框，允许用户点击搜索结果
 */
const handleBlur = (event: FocusEvent) => {
  // console.log('🔍 搜索框失去焦点')
  // 检查焦点是否移动到下拉框内
  const relatedTarget = event.relatedTarget as HTMLElement
  if (relatedTarget && searchContainer.value?.contains(relatedTarget)) {
    // 焦点在搜索组件内，不关闭下拉框
    return
  }

  // 延迟关闭，允许点击下拉项
  setTimeout(() => {
    // console.log('🔍 焦点丢失延迟关闭下拉框')
    showDropdown.value = false
  }, 300) // 增加延迟时间
}

/**
 * 处理键盘导航事件
 * 支持上下箭头选择、回车确认、ESC退出
 */
const handleKeydown = (event: KeyboardEvent) => {
  if (!showDropdown.value || !suggestions.value) return

  const suggestionsLength = suggestions.value?.length || 0
  const maxIndex = suggestionsLength + (totalCount.value > suggestionsLength ? 1 : 0) - 1
  
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedIndex.value = Math.min(selectedIndex.value + 1, maxIndex)
      break
    case 'ArrowUp':
      event.preventDefault()
      selectedIndex.value = Math.max(selectedIndex.value - 1, -1)
      break
    case 'Enter':
      event.preventDefault()
      if (selectedIndex.value >= 0 && suggestions.value) {
        if (selectedIndex.value < suggestions.value.length) {
          handleItemClick(suggestions.value[selectedIndex.value])
        } else {
          handleViewMore()
        }
      }
      break
    case 'Escape':
      showDropdown.value = false
      selectedIndex.value = -1
      break
  }
}

/**
 * 处理搜索项点击事件
 * 根据项目类型执行不同的跳转逻辑
 */
const handleItemClick = (item: SearchSuggestion) => {
  // console.log('🔍 点击搜索项:', {
  //   name: item.name,
  //   type: item.type,
  //   folderId: item.folderId,
  //   parentFolder: item.parentFolder,
  //   fullItem: item
  // })

  showDropdown.value = false
  searchKeyword.value = ''

  if (item.type === 'folder') {
    // 跳转到文件夹
    const targetQuery = { folderId: item.folderId }
    // console.log('🔍 跳转到文件夹:', targetQuery)
    router.push({
      path: '/dashboard/files',
      query: targetQuery
    })
  } else {
    // 跳转到文件所在文件夹并高亮文件
    const fileId = item.id.replace('file_', '') // 移除前缀
    const targetQuery = {
      parentId: item.folderId || '0',
      highlightFile: fileId
    }
    // console.log('🔍 跳转到文件所在文件夹:', targetQuery)
    router.push({
      path: '/dashboard/files',
      query: targetQuery
    })
  }
}

/**
 * 处理"查看更多结果"点击事件
 * 跳转到文件页面执行完整搜索
 */
const handleViewMore = () => {
  showDropdown.value = false
  const keyword = searchKeyword.value
  searchKeyword.value = ''

  // 跳转到文件页面执行完整搜索
  router.push({
    path: '/dashboard/files',
    query: { search: keyword }
  })
}

/**
 * 处理搜索框清空事件
 * 重置所有搜索相关状态
 */
const handleClear = () => {
  showDropdown.value = false
  suggestions.value = []
  selectedIndex.value = -1
}

/**
 * 处理点击外部区域事件
 * 关闭搜索下拉框
 */
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (searchContainer.value && !searchContainer.value.contains(target)) {
    // console.log('🔍 点击外部，关闭下拉框')
    showDropdown.value = false
  }
}

// 组件挂载时添加全局点击监听
nextTick(() => {
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时移除监听
// onUnmounted(() => {
//   document.removeEventListener('click', handleClickOutside)
// })
</script>

<style lang="scss" scoped>
.global-search {
  position: relative;
  width: 300px;
  
  .search-dropdown {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    right: 0;
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    border-radius: 8px;
    box-shadow: var(--shadow-base);
    z-index: 2000;
    max-height: 400px;
    overflow-y: auto;
    transition: all 0.3s ease;

    /* 确保下拉框可以接收鼠标事件 */
    pointer-events: auto;

    /* 防止下拉框被其他元素遮挡 */
    isolation: isolate;
  }
  
  .search-loading {
    display: flex;
    align-items: center;
    padding: 16px;
    color: var(--text-color-secondary);
    transition: color 0.3s ease;

    .loading-icon {
      margin-right: 8px;
      animation: rotate 1s linear infinite;
    }
  }

  .no-results {
    padding: 16px;
    text-align: center;
    color: var(--text-color-secondary);
    transition: color 0.3s ease;

    .no-results-text {
      font-size: 14px;
    }
  }
  
  .search-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border-color-light);
    cursor: pointer;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &:hover,
    &.active {
      background-color: var(--bg-color-secondary);
    }

    &.more-results {
      color: var(--theme-primary);
      font-weight: 500;
    }

    .item-icon {
      margin-right: 12px;
      font-size: 18px;
      color: var(--text-color-secondary);
      transition: color 0.3s ease;
    }

    .item-content {
      flex: 1;
      min-width: 0;

      .item-name {
        font-size: 14px;
        color: var(--text-color-primary);
        margin-bottom: 2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        transition: color 0.3s ease;
      }

      .item-meta {
        font-size: 12px;
        color: var(--text-color-secondary);
        display: flex;
        gap: 8px;
        transition: color 0.3s ease;
        
        .parent-folder::before {
          content: "📁 ";
        }
        
        .file-size::before {
          content: "📊 ";
        }
        
        .modified-time::before {
          content: "🕒 ";
        }
      }
    }
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .global-search {
    width: 200px;
  }
}
</style>
